package com.cc.shriojwtredis.wanling.controller;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: cc
 * @Date: 2024/04/19/14:45
 **/

import com.cc.shriojwtredis.wanling.domain.RegisterUser;
import com.cc.shriojwtredis.wanling.service.UserService;
import com.cc.shriojwtredis.wanling.utils.RedisUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@Controller
@Api(tags = "验证码获取接口")
public class CommonController {
    @Autowired
    private UserService userService;

    @Autowired
    private DefaultKaptcha captchaProducer;

    @PostMapping("/common/kaptcha")
    @ResponseBody
    @ApiOperation("验证码生成获取")
    public String defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, @RequestBody RegisterUser registerUser) throws Exception {
        //用户已经存在，不允许后续操作
        if(userService.getUserByAccount(registerUser.getAccount())!=null){
            HashMap<String,Object> hs=new HashMap<>();
            hs.put("error","用户账号已存在！");
            ObjectMapper objectMapper=new ObjectMapper();
            return objectMapper.writeValueAsString(hs);
        }else {
            //先验证1分钟内该用户是否请求过验证码，避免暴力请求接口
            if(RedisUtil.get(registerUser.getAccount())==null) {
                //发送验证码，将验证码存到Redis
                String verifyCode = captchaProducer.createText();
                HashMap<String, Object> hs = new HashMap<>();
                RedisUtil.set(registerUser.getAccount(), verifyCode, 60);
                hs.put("info", "成功访问验证码接口！");
                hs.put("code", verifyCode);
                ObjectMapper objectMapper = new ObjectMapper();
                return objectMapper.writeValueAsString(hs);
            }else{
                HashMap<String, Object> hs = new HashMap<>();
                hs.put("error", "已经在一分钟内请求过验证码，请稍后再试");
                ObjectMapper objectMapper = new ObjectMapper();
                return objectMapper.writeValueAsString(hs);
            }
        }
    }
}